'''
 RLock允许在同一线程中被多次acquire。而Lock却不允许这种情况。注意：如果使用RLock，那么acquire和release必须成对出现，即调用了n次acquire，必须调用n次的release才能真正释放所占用的琐。
'''
import time,threading

# 假定这是你的银行存款:
balance = 0
rlock = threading.RLock()

def change_it(n):
    # 先存后取，结果应该为0:
    global balance
    balance = balance+n
    balance = balance-n


def run_thread(n):
    for i in range(100000):
        #获取锁
        rlock.acquire()
        try:
            #放心改
            change_it(i)
        finally:
            #修改完后释放锁
            rlock.release()




def main():
    t1 = threading.Thread(target=run_thread,args=(5,))
    t2 = threading.Thread(target=run_thread,args=(8,))

    t1.start()
    t2.start()

    t1.join()
    t2.join()

    print(balance)
    

if __name__ == "__main__":
    main()
